﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace StyleMVVM.DependencyInjection.Conditions
{
	public sealed class WhenMemberHas : IExportCondition
	{
		private Type attributeType;

		public WhenMemberHas(Type attributeType)
		{
			this.attributeType = attributeType;
		}

		public bool ConditionMeet(IDependencyInjectionContainer container,
		                          IInjectionContext injectionContext,
		                          IExportStrategy exportStrategy)
		{
			IInjectionTargetInfo targetInfo = injectionContext.Target;

			if (targetInfo != null)
			{
				PropertyInfo propertyInfo = targetInfo.InjectionTarget as PropertyInfo;
				object[] attributes = null;

				if (propertyInfo != null)
				{
					attributes = targetInfo.InjectionTargetAttributes;
				}
				else
				{
					ParameterInfo parameterInfo = targetInfo.InjectionTarget as ParameterInfo;

					if (parameterInfo != null)
					{
						attributes = parameterInfo.Member.GetCustomAttributes().ToArray();
					}
				}

				if (attributes != null)
				{
					foreach (object attribute in attributes)
					{
						if (attributeType.GetTypeInfo().IsAssignableFrom(attribute.GetType().GetTypeInfo()))
						{
							return true;
						}
					}
				}
			}

			return false;
		}
	}
}